package com.woniuxy.opencv.controller;

import com.woniuxy.opencv.pojo.ParkingOrder;
import com.woniuxy.opencv.service.AlipayService;
import com.woniuxy.opencv.service.ParkingOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/pay")
public class PaymentController {

    @Autowired
    private AlipayService alipayService;

    @Autowired
    private ParkingOrderService parkingOrderService;

    /**
     * 创建支付订单
     */
    @PostMapping("/create/{orderId}")
    public ResponseEntity<Map<String, Object>> createPayment(@PathVariable String orderId) {
        Map<String, Object> result = new HashMap<>();
            log.info("接收到创建支付订单请求 - 订单号: {}", orderId);
            // 将字符串orderId转换为Long类型
            Long orderIdLong;
            orderIdLong = Long.parseLong(orderId);
            // 获取订单信息
            ParkingOrder order = parkingOrderService.getById(orderIdLong);
            if (order == null) {
                log.error("订单不存在: {}", orderId);
                result.put("success", false);
                result.put("message", "订单不存在");
                return ResponseEntity.badRequest().body(result);
            }
            // 创建支付订单
            String url = alipayService.createPayment(order);
            if (url == null) {
                log.error("创建支付订单失败: {}", orderId);
                result.put("success", false);
                result.put("message", "创建支付订单失败");
                return ResponseEntity.badRequest().body(result);
            }
            log.info("创建支付订单成功 - 订单号: {}", orderId);
            result.put("success", true);
            result.put("url", url);
            result.put("orderId", orderId);
            result.put("amount", order.getFee());
            return ResponseEntity.ok(result);

    }

    /**
     * 查询支付状态
     */
    @GetMapping("/status/{orderId}")
    public ResponseEntity<Map<String, Object>> queryPaymentStatus(@PathVariable String orderId) {
        Map<String, Object> result = new HashMap<>();
        

            log.info("查询支付状态 - 订单号: {}", orderId);
            boolean isPaid = alipayService.queryPaymentStatus(orderId);
            result.put("success", true);
            result.put("paid", isPaid);
            return ResponseEntity.ok(result);

    }

    /**
     * 模拟支付成功
     */
    @PostMapping("/mock/success/{orderId}")
    public ResponseEntity<Map<String, Object>> mockPaymentSuccess(@PathVariable String orderId) {
        Map<String, Object> result = new HashMap<>();
            log.info("模拟支付成功 - 订单号: {}", orderId);
            alipayService.mockPaymentSuccess(orderId);
            result.put("success", true);
            result.put("message", "支付成功");
            return ResponseEntity.ok(result);
    }
} 